const { format } = require('date-fns');
const { withRetry } = require('../playwright-operation/playwrightUtils');

class OrderDetailPage {
    constructor(page) {
        this.page = page;
    }

    async clickTabQuotation() {
        await this.page.locator('#tab-quotation').click();
    }

    async clickTabSubcontract() {
        await this.page.getByRole('tab', {name: 'Subcontract'}).click();
        // await this.page.locator('#tab-subContract').click();
    }

    async clickAllSave() {
        const allSaveXpath = '//div[@class="sgs-footer orderFooter el-row"]//button[normalize-space()="Save"][last()]';
        await this.page.locator(allSaveXpath).click();
    }

    async quaPageCheckboxAll() {
        // const checkboxAllXpath = '//*[@id="generalQuotation"]/div[2]/div[3]/div/div/div[4]/div[1]/table/thead/tr/th[2]/div/label/span/span';
        const checkboxAllXpath = '//*[@id="generalQuotation"]/div[2]/div[2]/div[3]/div/div/div[4]/div[1]/table/thead/tr/th[2]/div/label/span/span';
        await this.page.locator(checkboxAllXpath).click();
    }

    async quaPageClickAssignSample() {
        await this.page.getByRole('button', {name: 'Assign Sample'}).click();
    }

    async quaPageAssignSampleCheckboxAll() {
        const assignSampleCheckboxAllXpath = '//div[@aria-label="Assign Sample"]/div[2]/div/div[2]/table/thead/tr/th[1]/div/label/span/span';
        await this.page.locator(assignSampleCheckboxAllXpath).click();
    }

    async quaPageAssignSampleClickSave() {
        const assignSampleSaveXpath = '//div[@aria-label="Assign Sample"]/div[3]/span/button[1]';
        await this.page.locator(assignSampleSaveXpath).click();
    }

    async clickSave() {
        // const saveXpath = '//*[@id="generalQuotation"]/div[2]/div[2]/div/div[3]/div/button[1]';
        const saveXpath = '//*[@id="generalQuotation"]/div[2]/div[2]/div/div/div[3]/div/button[1]';
        const save = this.page.locator(saveXpath);
        if (save && !await save.getAttribute('disabled')) {
            await this.page.locator(saveXpath).click();
        }
    }

    async clickGenerate() {
        // const generateXpath = '//*[@id="generalQuotation"]/div[2]/div[2]/div/div[3]/div/button[2]';
        const generateXpath = '//*[@id="generalQuotation"]/div[2]/div[2]/div/div/div[3]/div/button[2]';
        const generate = this.page.locator(generateXpath);
        if (generate && !await generate.getAttribute('disabled')) {
            await this.page.locator(generateXpath).click();
        }
    }

    async clickConfirm() {
        // const confirmXpath = '//*[@id="generalQuotation"]/div[2]/div[2]/div/div[3]/div/button[3]';
        const confirmXpath = '//*[@id="generalQuotation"]/div[2]/div[2]/div/div/div[3]/div/button[3]';
        const confirm = this.page.locator(confirmXpath);
        if (confirm && !await confirm.getAttribute('disabled')) {
            await this.page.locator(confirmXpath).click();
        }
    }

    async getWarningOrSelectApprove() {
        const selectApproveLocator = this.page.locator('//div[@aria-label="Select Approve"]/..');
        const warningLocator = this.page.locator('//div[@aria-label="Warning"]');
        try {
            const [selectApproveElement] = await selectApproveLocator.elementHandles();
            const [warningElement] = await warningLocator.elementHandles();

            return { selectApprove: selectApproveElement, warning: warningElement };
        } catch (error) {
            console.error('Error retrieving elements:', error);
            return {};
        }
    }

    async clickConfirmOrder() {
        await this.page.getByRole('button', {name: 'Confirm Order', exact: true}).click();
        // const confirmOrderXpath = '//*[@id="orderInfo"]/div[2]/span[1]/button/span';
        // await this.page.locator(confirmOrderXpath).click();
        // await this.page.getByRole('button', {name: 'Confirm Order'}).click();
    }

    async subConPageClickNewSubcontract() {
        const newSubcontractXpath = '//*[@id="sub-contract-list"]/div[1]/div/div[1]/div[1]/button[1]/span';
        await this.page.locator(newSubcontractXpath).click();
    }

    // Subcontract TestLines
    async subConPageEditSubcontractPageCheckboxAll() {
        // const editSubcontractXpath = '//*[@aria-label="Edit Subcontract"]';
        const checkboxAllXpath = '//*[@aria-label="Edit Subcontract"]/div[2]/div/div[5]/div[1]/div[1]/div[4]/div[1]/table/thead/tr/th[1]/div/label/span/span';
        // const editSubcontract = this.page.locator(editSubcontractXpath);
        await this.page.locator(checkboxAllXpath).click();
    }

    async subConPageEditSubcontractPageSearchBU(subcontractLab) {
        const searchBUXpath = '//*[@id="sub-contract-list"]/div[3]/div/div[2]/div/div[5]/div[1]/div[1]/div[2]/table/thead/tr/th[7]/div/span';
        await this.page.locator(searchBUXpath).click();
        const inputBUXpath = '//*[@id="sub-contract-list"]/div[3]/div/div[2]/div/div[5]/div[1]/div[1]/div[2]/table/thead/tr/th[7]/div/div/input';
        const buMap = {
            'CCL': 'CChemLab',
            'SL': 'SL',
            'FTS': 'FTS',
            'AFL': 'AFL',
            'HL': 'HL',
            'EMC': 'E&E',
            'IND-CCM': 'IND-CCM',
            'MR': 'MR',
            'CPCH': 'CPCH'
        };

        for (const key in buMap) {
            if (subcontractLab.includes(key)) {
                await this.page.locator(inputBUXpath).fill(buMap[key]);
                break;
            }
        }
    }

    async subConPageEditSubcontractPageCheckBUByRow(page) {
        const tbodyElementXpath = '//*[@id="sub-contract-list"]/div[3]/div/div[2]/div/div[5]/div[1]/div[1]/div[3]/table/tbody';
        const tdInRowXPath = (rowIndex, tdIndex) =>
            `//*[@id="sub-contract-list"]/div[3]/div/div[2]/div/div[5]/div[1]/div[1]/div[3]/table/tbody/tr[${rowIndex}]/td[${tdIndex}]`;
        const divInTdXPath = (tdXPath) => `${tdXPath}/div`;
        const spanInDivXPath = (divXPath) => `${divXPath}/span`;

        const tbodyElement = await page.$(tbodyElementXpath);

        if (!tbodyElement) {
            console.log('The specified tbody element was not found.');
            return;
        }
        // Get the count of tr rows
        const trCount = await tbodyElement.evaluate((el) => el.childElementCount);
        console.log(`The tbody contains ${trCount} tr rows.`);

        // Iterate over each tr row
        for (let rowIndex = 1; rowIndex <= trCount; rowIndex++) {
            const fifthTdXPath = tdInRowXPath(rowIndex, 5);
            const fifthTdDivXPath = divInTdXPath(fifthTdXPath);
            const fifthTdSpanXPath = spanInDivXPath(fifthTdDivXPath);
            let BU = await page.locator(fifthTdSpanXPath).textContent();

            // Check if the span text in the 5th TD matches the given subcontractLab
            if(BU){
                const isMatch = BU.includes("SL") || BU.includes("HL");
                if (isMatch) {
                    const firstTdXPath = tdInRowXPath(rowIndex, 1);
                    const firstTdDivXPath = divInTdXPath(firstTdXPath);
                    const firstTdLabelXPath = `${firstTdDivXPath}/label`;
                    const checkBoxSpanXPath = `${firstTdLabelXPath}/span`;
                    await page.$eval(checkBoxSpanXPath, (checkbox) => {
                        checkbox.click();
                    });                    
                }
            }
        }
    }

    // Subcontract to
    async subConPageSubContractToQueryLabClick() {
        const searchXpath = '//*[@aria-label="Edit Subcontract"]/div[2]/div/div[7]/form/div[1]/div/div/div/div/button';
        await this.page.locator(searchXpath).click();
    }

    async subConPageQueryLabInput(labCode, contactName) {
        // console.log('labCode:'+labCode + ' contactName:' + contactName)
        const labCodeXpath = '//*[@aria-label="Query Lab"]/div[2]/div/form/div[1]/div/div/div/input';
        const contactNameXpath = '//*[@aria-label="Query Lab"]/div[2]/div/form/div[3]/div/div/div/input';
        const searchXpath = '//*[@aria-label="Query Lab"]/div[2]/div/form/div[4]/button';
        const firstTdXpath = '//*[@aria-label="Query Lab"]/div[2]/div/div/div/div[1]/div[3]/table/tbody/tr[1]/td[1]';
        const queryLabSaveXpath = '//*[@aria-label="Query Lab"]/div[3]/div/button[1]/span';
        if (contactName !== '') {
            /*console.log('labCode!:'+labCode)
            console.log('contactName!:'+contactName)*/
            await this.page.locator(labCodeXpath).fill(labCode);
            await this.page.locator(contactNameXpath).fill(contactName);
        }else{
            await this.page.locator(labCodeXpath).fill(labCode);
        }
        await this.page.locator(searchXpath).click();
        await this.page.locator(firstTdXpath).click();
        await this.page.locator(queryLabSaveXpath).click();
    }

    async subConPageSubConContact(subcontractContact) {
        if (subcontractContact && subcontractContact !== '') {
            await this.page.getByPlaceholder('Pls Input Subcontract Contact...')
                .first()
                .fill(subcontractContact);
        }
    }

    // Headers
    async subConPageEditSubcontractSubConExpDueDate(expectDueDate) {
        if (expectDueDate && expectDueDate !== '') {
            const dueDateAsDate = new Date(expectDueDate);
            let expectDueDateStr = dueDateAsDate.toISOString().substring(0,10);
            await this.page.locator('//input[@placeholder="Pls Select Expect Due Date..."]').click();
            await this.page.getByPlaceholder('Select date').first().fill(format(expectDueDateStr, 'yyyy-MM-dd'));
            await this.page.getByPlaceholder('Select time').first().fill(format(expectDueDateStr, 'HH:mm:ss'));
        }
    }

    async subCon_page_editSubcontract_remark(subcontract_remark) {
        if (subcontract_remark && subcontract_remark !== '') {
            await this.page.getByPlaceholder('Pls Input Remark...').click();
            await this.page.getByPlaceholder('Pls Input Remark...').first().fill(subcontract_remark);
        }
    }

    async subCon_page_editSubcontract_subcontractFee(subcontract_fee) {
        const subCon_fee_Xpath = '//*[@role="spinbutton"][@aria-valuemin="0"]';
        if (subcontract_fee && subcontract_fee !== '') {
            console.log('subcontract_fee:'+subcontract_fee);
            await this.page.locator(subCon_fee_Xpath).first().click();
            await this.page.keyboard.press('Control+A');
            await this.page.locator(subCon_fee_Xpath).first().fill(String(subcontract_fee));
        }
    }

    async subCon_page_editSubcontract_softCopyDeliveryTo(softCopyDeliveryTo) {
        try {
            // const others_textarea_Xpath = '//*[@id="testRequest"]/form/div/div[19]/div/div/div/div/div[2]/textarea';
            const others_textarea_Xpath = 'textarea[placeholder="多个邮箱以\';\'分割"]';
            if (softCopyDeliveryTo && softCopyDeliveryTo !== ' ') {
                await this.page.locator(others_textarea_Xpath).nth(1).click();
                await this.page.keyboard.press('Control+A');
                await this.page.locator(others_textarea_Xpath).nth(1).fill(softCopyDeliveryTo);
            }
        } catch (error) {
            console.log(error);
        }
    }

    async subCon_page_editSubcontract_accreditationRequest(accreditationRequest) {
        try {
            if (accreditationRequest && accreditationRequest !== '') {
                const CMA_Xpath = '//*[@id="testRequest"]/form/div/div[4]/div/div/div/div/label[1]/span[1]/span';
                const CMA_label_Xpath = '//*[@id="testRequest"]/form/div/div[4]/div/div/div/div/label[1]';
                const CNAS_Xpath = '//*[@id="testRequest"]/form/div/div[4]/div/div/div/div/label[2]/span[1]/span';
                const CNAS_label_Xpath = '//*[@id="testRequest"]/form/div/div[4]/div/div/div/div/label[2]';
                const UKAS_Xpath = '//*[@id="testRequest"]/form/div/div[4]/div/div/div/div/label[3]/span[1]/span';
                const UKAS_label_Xpath = '//*[@id="testRequest"]/form/div/div[4]/div/div/div/div/label[3]';
                const HOKLAS_Xpath = '//*[@id="testRequest"]/form/div/div[4]/div/div/div/div/label[4]/span[1]/span';
                const HOKLAS_label_Xpath = '//*[@id="testRequest"]/form/div/div[4]/div/div/div/div/label[4]';
    
                if (accreditationRequest.includes('CMA')) {
                    const a = this.page.locator(CMA_label_Xpath);
                    const className = await a.getAttribute('class');
                    // 确保 className 不为 null 并且包含 'is-checked'
                    if (className && !className.includes('is-checked')) {
                        await this.page.locator(CMA_Xpath).click();
                    }
                }
                if (accreditationRequest.includes('CNAS')) {
                    const a = this.page.locator(CNAS_label_Xpath);
                    const className = await a.getAttribute('class');
                    // 确保 className 不为 null 并且包含 'is-checked'
                    if (className && !className.includes('is-checked')) {
                        await this.page.locator(CNAS_Xpath).click();
                    }
                }
    
                if (accreditationRequest.includes('UKAS')) {
                    const a = this.page.locator(UKAS_label_Xpath);
                    const className = await a.getAttribute('class');
                    // 确保 className 不为 null 并且包含 'is-checked'
                    if (className && !className.includes('is-checked')) {
                        await this.page.locator(UKAS_Xpath).click();
                    }
                }
    
                if (accreditationRequest.includes('HOKLAS')) {
                    const a = this.page.locator(HOKLAS_label_Xpath);
                    const className = await a.getAttribute('class');
                    // 确保 className 不为 null 并且包含 'is-checked'
                    if (className && !className.includes('is-checked')) {
                        await this.page.locator(HOKLAS_Xpath).click();
                    }
                }
            }
        } catch (error) {
            console.log(error);
        }
    }

    async subCon_page_editSubcontract_returnSampleTo(email) {
        try {
            const return_sample_to_Xpath = '//*[@id="testRequest"]/form/div/div[20]/div/div/div/div/div[2]/textarea';
            if (email && email !== '') {
                await this.page.locator(return_sample_to_Xpath).click();
                await this.page.keyboard.press('Control+A');
                await this.page.locator(return_sample_to_Xpath).fill(email);
            }
        } catch (error) {
            console.log(error);
        }
        
    }

    async selectReturnSampleWay(returnSampleWay) {
        try {
            const residue_sample_Xpath = '//*[@aria-label="Edit Subcontract"]/div[2]/div/div[10]/div[2]/form/div/div[14]/div/div/div/div/label[1]/span[1]';
            const tested_sample_Xpath = '//*[@aria-label="Edit Subcontract"]/div[2]/div/div[10]/div[2]/form/div/div[14]/div/div/div/div/label[2]/span[1]';
            if (returnSampleWay === 'yes') {
                await this.page.locator(residue_sample_Xpath).click();
                await this.page.locator(tested_sample_Xpath).click();
            }
        } catch (error) {
            console.log(error);
        }
    }

    async subCon_page_editSubcontract_reportRequirement(report_requirement) {
        try {
            const report_requirement_Xpath = '//*[@id="testRequest"]/form/div/div[25]/div/div/div/div[1]/div/div/div[1]';
            await this.page.locator(report_requirement_Xpath).click();
    
            let visibleOption = null;
    
            switch (report_requirement.toLowerCase()) {
                case 'pdf':
                    for (const option of await this.page.$$('li:has-text("Customer Report(PDF)")')) {
                        if (await option.isVisible()) {
                            visibleOption = option;
                            break;
                        }
                    }
                    break;
                case 'word':
                    for (const option of await this.page.$$('li:has-text("Sub Report (Word)")')) {
                        if (await option.isVisible()) {
                            visibleOption = option;
                            break;
                        }
                    }
                    break;
            }
    
            if (visibleOption) {
                await visibleOption.click();
            } else {
                throw new Error(`No visible "${report_requirement.toUpperCase()}" option found.`);
            }
        } catch (error) {
            console.error('Error during report requirement selection:', error);
        }
    }

    async subCon_page_editSubcontract_save() {
        const save_Xpath = '//*[@aria-label="Edit Subcontract"]/div[2]/div/div[11]/button[2]';
        await this.page.locator(save_Xpath).click();
    }

    /*async subCon_page_toStarLIMSIcon_click() {
        const parentElement = await this.page.locator('div.el-table__body-wrapper.is-scrolling-right');
        await parentElement.locator('i.el-icon-guide').click();
    }*/

    async subCon_page_trs_num() {
        const tbody_Xpath = '//*[@id="sub-contract-list"]/div[1]/div/div[2]/div[3]/table/tbody';
        return await this.page.$$eval(tbody_Xpath + '/tr', (trs) => trs.length);
    }

    async subCon_page_cells_value(order_no) {
        const rowsNo = await this.subCon_page_trs_num();
        for (let i = 0; i < rowsNo; i++) {
            const tr_No = `tr[${i + 1}]`;
            const orderNo_Xpath = `//*[@id="sub-contract-list"]/div[1]/div/div[2]/div[3]/table/tbody/${tr_No}/td[3]/div`;
            const status_Xpath = `//*[@id="sub-contract-list"]/div[1]/div/div[2]/div[3]/table/tbody/${tr_No}/td[11]/div/span`;
            const starLIMSIcon_Xpath = `//*[@id="sub-contract-list"]/div[1]/div/div[2]/div[5]/div[2]/table/tbody/${tr_No}/td[18]/div/button[2]`;
            const subContractTo_Xpath = `//*[@id="sub-contract-list"]/div[1]/div/div[2]/div[3]/table/tbody/${tr_No}/td[4]/div/span`;
            try {
                const [statusResult, orderNoResult, subContractToResult] = await Promise.all([
                    this.page.locator(status_Xpath).first().textContent(),
                    this.page.locator(orderNo_Xpath).first().textContent(),
                    this.page.locator(subContractTo_Xpath).first().textContent()
                ]);

                const statusElement = statusResult?.trim();
                const orderNoElement = orderNoResult?.trim();
                const subContractToElement = subContractToResult?.trim();
                console.log(`订单号: ${orderNoElement}`);
                console.log(`状态: ${statusElement}`);
                console.log(`SubContractTo: ${subContractToElement}`);
                if (statusElement === 'New' && orderNoElement === order_no && subContractToElement?.includes('CCL')) {
                    // const row_Xpath = `//*[@id="sub-contract-list"]/div[1]/div/div[2]/div[3]/table/tbody/${tr_No}`;
                    // // 行
                    // const row = this.page.locator(row_Xpath);
                    // const rowExists = await row.count() > 0;
                    // console.log(`行定位 ${row_Xpath} 是否成功: ${rowExists}`);
                    // // 最后一个单元格
                    // const lastCell = row.locator('td').last().locator('div');
                    // const lastCellExists = await lastCell.count() > 0;
                    // console.log(`最后一个单元格定位是否成功: ${lastCellExists}`);
                    const toStarlimsButton_Xpath = `//*[@id="sub-contract-list"]/div[1]/div/div[2]/div[3]/table/tbody/${tr_No}/td[last()]/div/button/i[contains(@class, "el-icon-guide")]`;
                    return {
                        orderNo: orderNoElement,
                        subcontractTo: subContractToElement,
                        status: statusElement,
                        starLIMSIcon_Xpath: toStarlimsButton_Xpath,
                    };
                }
            } catch (error) {
                console.error('获取元素值时出错: ', error);
            }
        }
        return null; // 明确返回null而不是undefined
    }

    async toStarLIMSAlert() {
        const yesXpath = '//div[@aria-label="dialog"][@class="el-message-box__wrapper"]/div/div[3]/button[2]';
        const alertInfoXpath = '//div[@aria-label="dialog"][@class="el-message-box__wrapper"]/div/div[2]';
        const element = this.page.locator(alertInfoXpath);
        if (element) {
            const text = await this.page.locator(alertInfoXpath).textContent();
            if (text) {
                text.trim();
            }
            return [text, yesXpath];
        } else {
            return [null, yesXpath];
        }
    }

    async detailsToStarLIMSCheckboxAll() {
        // const checkboxAllXpath = '//div[@aria-label="DETAILS - TO STARLIMS"]/div[2]/div/div/div/div[1]/div[2]/table/thead/tr/th[1]/div/label/span/span';
        // const checkbox = this.page.locator('input[type="checkbox"]');
        const checkboxAllXpath1 = '//div[@aria-label="DETAILS - TO STARLIMS"]//span[@class="el-checkbox__inner"]';

        await this.page.locator(checkboxAllXpath1).nth(1).dispatchEvent('click');
    }

    async detailToStarLIMSConfirm() {
        // await this.page.getByRole('button', {name: 'Confirm'}).click();
        const confirmXpath = '//div[@aria-label="DETAILS - TO STARLIMS"]/div[2]/div[2]/div/button[2]';
        await this.page.locator(confirmXpath).click();
    }
}

module.exports = { OrderDetailPage };